var capabilities = null ; // global
var mapcache = null;
var mapUnits = {
    'dd' : 'grados',//tiene que ir en un archivo global
    'm' : 'metros'
}
$(document).ready( function() {
    
    centerSelectLayerWarningPopUp();
    initLayersGrid();
    configureControls();
        
  
})

function initLayersGrid () {
    //meter esta inicialización en una funcion
    format = new OpenLayers.Format.WMTSCapabilities({
        /**
         * This particular service is not in compliance with the WMTS spec and
         * is providing coordinates in y, x order regardless of the CRS.  To
         * work around this, we can provide the format a table of CRS URN that
         * should be considered y, x order.  These will extend the defaults on
         * the format.
         */
        yx: {
            "urn:ogc:def:crs:EPSG:6.3:4326": true
        }
    });
        
    OpenLayers.Request.GET({
        //Todo sacar harcodeo
        url: "/map.fcgi/wmts/1.0.0/WMTSCapabilities.xml",
        
        success: function(request) {
            var doc = request.responseXML;
            if (!doc || !doc.documentElement) {
                doc = request.responseText;
            }
            capabilities = format.read(doc);
            
            // preparo los datos 
            var gridData = [];
            //inicializo los datos adicionales hago una sola llamada dentro del succes del capabilities
            $.ajax({
                url : APPALIAS+'/layers/getInitialDataForGrid',
                type:'GET',
                dataType: 'json',
                success: function(data) {
                    
                    mapcacheData = data;
                   
                    $.each (capabilities.contents.layers , function(index,layer){
                               
                        // Creo el dropdown de los formatos
                        var formatSelect = $('<select></select>');
                        $.each(layer.formats, function(i, value) {   
                
                            formatSelect
                            .append($("<option></option>")
                                .attr("value",value)
                                .text(value)); 
                        });
                        // fin creo el dropdown de los formatos
                
                        // creo el dropdown de los SRS
                        var srsSelect = $('<select></select>').addClass('gridSrsSelector');
                        $.each(layer.tileMatrixSetLinks, function(i, value) {   
                
                            srsSelect
                            .append($('<option></option>')
                                .attr('value',value.tileMatrixSet)
                                .text(value.tileMatrixSet).attr('index',i));
                    
                        }); // fin creo el dropdown  de los SRS
                        
                        var layerSRSData = mapcacheData.layers[ layer.title].grids[layer.tileMatrixSetLinks[0].tileMatrixSet];
                        var defaultSRSData = mapcacheData.grids[layer.tileMatrixSetLinks[0].tileMatrixSet];
                        var defaultSRSMaxZoom = capabilities.contents.tileMatrixSets[layer.tileMatrixSetLinks[0].tileMatrixSet].matrixIds.length -1;
                        var minZoom = layerSRSData["@attributes"] && layerSRSData["@attributes"]["minzoom"] ? layerSRSData["@attributes"]["minzoom"] : "0";
                        var maxZoom = layerSRSData["@attributes"] && layerSRSData["@attributes"]["maxzoom"] ? layerSRSData["@attributes"]["maxzoom"] : defaultSRSMaxZoom.toString();
                        var layerObject = {
                            layerTitle : layer.title,
                            format: layer.formats[0], //por ahora es 1 formato por capa
                            bbox : layerSRSData["@attributes"] && layerSRSData["@attributes"]["restricted_extent"] ? layerSRSData["@attributes"]["restricted_extent"]  : defaultSRSData.extent.toString() ,
                            srs: srsSelect[0].outerHTML,
                            resolutions : defaultSRSData.resolutions,
                            units: mapUnits[defaultSRSData.units],
                            minzoom: minZoom,
                            maxzoom: maxZoom
                        };
                        gridData[index]=layerObject;
             
                    } );
                    //Inicializo la tabla de layers
                    $('#layers').jqGrid(
                    {
                        datatype : 'local',
                        data: gridData,
                        height: '230px',
                        width: '1000px',
                        rowNum: 10,
                        colNames: ['Capa', 'SRS' , 'Formato' ,'Unidad','Min','Max','Bounding Box','Resoluciones'],
                        colModel:[
                        {
                            name:'layerTitle', 
                            width:140
                        },

                        {
                            name:'srs', 
                            width:120,
                            align:"center",
                            sortable: false
                            
                   
                        },

                        {
                            name:'format', 
                            width:100,
                            align:"center",
                            sortable: false
                    
                        },
                        {
                            name:'units', 
                            width:50, 
                            align:"center",
                            sortable: false
                        },
                        {
                            name:'minzoom', 
                            width:50, 
                            align:"center",
                            sortable: false
                        }, 
                        {
                            name:'maxzoom', 
                            width:50, 
                            align:"center",
                            sortable: false
                        },
                            

                        {
                            name:'bbox', 
                            width:250, 
                            align:"center",
                            sortable: false
                        },
                        {
                            name:'resolutions', 
                            width:250,
                            editable:true,
                            editType:'select',
                            align:"center",
                            sortable: false,
                            hidden: true
                        }
                   
                        ],
                        caption: "Capas Configuradas en Caché",
                        cellEdit: true,
                        cellsubmit: 'clientArray',
                        gridview: true,
                        pager: '#pager'
                
                    });
                    $('#layers').jqGrid('setGroupHeaders', {
                        useColSpanStyle: false, 
                        groupHeaders:[
                        {
                            startColumnName: 'minzoom', 
                            numberOfColumns: 2, 
                            titleText: 'Niveles de Zoom'
                        }
                        ]	
                    });
                    $('#layers').jqGrid('navGrid', '#pager', {
                        add: true, 
                        addtitle: 'Agregar nueva capa a la caché',
                        addfunc : function() {
                            window.location.replace('manageLayer');
                        },
                        del: true,
                        deltitle: 'Eliminar capa seleccionada',
                        delfunc: function (rowId) {
                            wrapRemoveLayer(rowId);
                        },
                        edit: true,
                        edittitle: 'Editar configuración de la capa seleccionada',
                        editfunc: function (rowId) {
                            goToUpdateLayerCacheConfig(rowId);
                        },
                        view:true,
                        viewtitle: 'Visualizar capa seleccionada',
                
                        viewfunc: function (rowId) {
                            viewLayer(rowId);  
                        },
                        viewicon: 'ui-icon-image',
                        refresh: false,
                        search: false
                    });
                    $("#layers")
                    .navGrid('#pager',{
                        edit:false,
                        add:false,
                        del:false,
                        search:false
                    })
                    .navButtonAdd('#pager',{
                        caption:'',
                        title:'Administrar la caché de la capa seleccionada', 
                        buttonicon:'ui-icon-gear', 
                        onClickButton: function(){ 
                            var rowId = $('#layers').jqGrid('getGridParam', 'selrow');
                            if (rowId) {
                                goToAdminLayer(rowId);
                            }
                            else {
                                var alertIDs = {
                                    themodal:'alertmod',
                                    modalhead:'alerthd',
                                    modalcontent:'alertcnt'
                                };
                                if ($("#"+alertIDs.themodal).length == 0 || $("#"+alertIDs.themodal).length === null ) {
                                    $.jgrid.createModal(alertIDs,"<div>"+$.jgrid.nav.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",
                                    {
                                        gbox:"#gbox_"+$.jgrid.jqID(this.p.id),
                                        jqModal:true,
                                        drag:true,
                                        resize:true,
                                        caption:$.jgrid.nav.alertcap,
                                        top:100,
                                        left:100,
                                        width:200,
                                        height: 'auto',
                                        closeOnEscape:true,
                                        zIndex: null
                                    },"","",true);
                                }
                                $.jgrid.viewModal("#"+alertIDs.themodal,{
                                    gbox:"#gbox_"+$.jgrid.jqID(this.p.id),
                                    jqm:true
                                });
                                $("#jqg_alrt").focus();
                            }
                        }, 
                        position:'last'
                    });
            

                    $(document).delegate('.gridSrsSelector','change',function(){
                        var rowId = $(this).parent().parent().attr('id');
                        updateSRSBbox(rowId ,$(this).val());
                    });
                }
            // End of success datos adicionales
                
            });
            
         
            
        },
        failure: function() {
            alert("No se pudo obtener el documento Capabilities");
            OpenLayers.Console.error.apply(OpenLayers.Console, arguments);
        }
    });
}

function wrapRemoveLayer(selrow){
    var rowData = $('#layers >tbody > #'+selrow);
    var layer = rowData.children('[aria-describedby = layers_layerTitle]').text();
    // Seteo el texto del dialogo
    
    var dialog = $('#deleteLayerDialog');
    var dialogContent = $('<p></p>').text('¿ Está Seguro de eliminar la capa '+ layer + ' ?').css('text-align','center');
    var deleteTilesCheckbox =  $('<input></input>').attr('id','deleteTiles').attr('type','checkbox').attr('checked',false);
    var deleteTilesCheckboxLabel = $('<label></label>').attr('for','deleteTiles').text('Eliminar teselas almancenadas');
    
    dialogContent.appendTo(dialog);
    deleteTilesCheckbox.appendTo(dialog);
    deleteTilesCheckboxLabel.appendTo(dialog);
    
   
    
    dialog.dialog({
        width: 'auto',
        height: 'auto',
        modal:true,
        title: 'Confirmación',
        buttons:[{
            text: 'Si', 
            click: function() {
                removeLayer(rowData,$('#deleteTiles',dialog)[0].checked);
                $(this).dialog('close');
            }
        },
        {
            text: 'No',
            click: function() {
                $(this).dialog('close');
                    
            }
                
        }
        ],
        close: function(e) {
            $(this).html('');
        }
    });
}

function removeLayer(rowData,deleteTiles) {
    
    // no utilizo las funciones de jqgri porque asi es mas facil obtener a ocion elegida en los drop de srs y format
    // obtengo parámetros
    var layer = rowData.children('[aria-describedby = layers_layerTitle]').text();
   
    $.ajax({
        url: APPALIAS+'/manageLayer/removeLayer',
        type: 'POST',
        data: {
            'layerWMTS': layer,
            'deleteTiles': deleteTiles
        },
        dataType: 'json',
        success: function(data){
            $('#layers').jqGrid('delRowData',rowData.attr('id'));
            openSuccessDeleteLayerDialog(data.layer);
            $('#layers').trigger('reloadGrid');
        
        } 
    });
   
}
 
function openSuccessDeleteLayerDialog(layer) {
    $('#successDeleteLayerDialog p').text('La capa '+ layer + ' fue eliminada').css('text-align','center');
    $('#successDeleteLayerDialog').dialog({
        width: 'auto',
        height: 'auto',
        modal:true,
        title: 'Éxito',
        buttons:[{
            text: 'Aceptar', 
            click: function() {
                $(this).dialog('close');
            }
        }
        ]
    }).open();
}
// Saco los datos de la fila
function viewLayer(selrow) {
    
    var rowData = $('#layers >tbody > #'+selrow); // no utilizo las funciones de jqgri porque asi es mas facil obtener a ocion elegida en los drop de srs y format
    // obtengo parámetros
    var layer = rowData.children('[aria-describedby = layers_layerTitle]').text();
    var srs = rowData.children('[aria-describedby = layers_srs]').children('select').val();
    var format = rowData.children('[aria-describedby = layers_format]').children('select').val();
    var units = rowData.children('[aria-describedby = layers_units]').text();
    var bbox = rowData.children('[aria-describedby = layers_bbox]').text();
    var minZoomLevel = rowData.children('[aria-describedby = layers_minzoom]').text();
    var maxZoomLevel = rowData.children('[aria-describedby = layers_maxzoom]').text();
    
    var form =  $('#formLayerViewContainer form');
    $('#layer').val(layer);
    $('#srs').val(srs);
    $('#format').val(format);
    $('#bbox').val(bbox);
    $('#minZoomLevel').val(minZoomLevel);
    $('#maxZoomLevel').val(maxZoomLevel);
    
    form.submit();
    
    
    
}
function goToAdminLayer(selrow) {
    var rowData = $('#layers >tbody > #'+selrow);
    var layer = rowData.children('[aria-describedby = layers_layerTitle]').text();
    var srs = rowData.children('[aria-describedby = layers_srs]').children('select').val();
    
    window.location.href='adminLayer/index/'+layer+'/'+encodeURIComponent(srs);
}

function goToUpdateLayerCacheConfig(selrow) {
    var rowData = $('#layers >tbody > #'+selrow);
    var layer = rowData.children('[aria-describedby = layers_layerTitle]').text();
    window.location.href='manageLayer/index/'+layer+'/1';
}

function updateSRSBbox(rowId, srs) {
    var rowData = $('#layers').jqGrid('getRowData', rowId);
    var grid = $('#layers');
    var layerSRSData = mapcacheData.layers[rowData.layerTitle].grids[srs];
    var defaultSRSData = mapcacheData.grids[srs];
    var defaultSRSMaxZoom = capabilities.contents.tileMatrixSets[srs].matrixIds.length -1;
                        
    var newBbox = layerSRSData["@attributes"] && layerSRSData["@attributes"]["restricted_extent"] ? layerSRSData["@attributes"]["restricted_extent"]  : defaultSRSData.extent ;
    var newUnits = mapUnits[defaultSRSData.units];
    var newMinZoom = layerSRSData["@attributes"] && layerSRSData["@attributes"]["minzoom"] ? layerSRSData["@attributes"]["minzoom"] : "0";
    var newMaxZoom = layerSRSData["@attributes"] && layerSRSData["@attributes"]["maxzoom"] ? layerSRSData["@attributes"]["maxzoom"] : defaultSRSMaxZoom.toString();
    var newResolutions = defaultSRSData.resolutions;
    
    grid.jqGrid('setCell', rowId, 'bbox', newBbox);
    grid.jqGrid('getLocalRow', rowId).bbox = newBbox;  
    
    grid.jqGrid('setCell', rowId, 'units', newUnits);
    grid.jqGrid('getLocalRow', rowId).units = newUnits;    
    
    grid.jqGrid('setCell', rowId, 'minzoom', newMinZoom);
    grid.jqGrid('getLocalRow', rowId).minzoom = newMinZoom;
    
    grid.jqGrid('setCell', rowId, 'maxzoom', newMaxZoom);
    grid.jqGrid('getLocalRow', rowId).maxzoom = newMaxZoom;
    
     
    grid.jqGrid('setCell', rowId, 'resolutions', newResolutions);
    grid.jqGrid('getLocalRow', rowId).resolutions = newResolutions;
    
}
function configureControls() {

    $('#goViewer').click(function(){
        window.location.href='basicViewer';
    }).button();
}
function centerSelectLayerWarningPopUp() {
    var orgViewModal = $.jgrid.viewModal;

    $.extend($.jgrid, {
        viewModal: function (selector, o) {
            if (selector === '#alertmod' || selector === '#alertmod_layers') {
                var $gbox = $(o.gbox), $selector = $(selector);
                var of = $gbox.offset(), w = $gbox.width(), h = $gbox.height(); 
                var w1 = $selector.width(), h1 = $selector.height();
                $selector.css({
                    'top': of.top + ((h-h1)/2),
                    'left': of.left + ((w-w1)/2)
                });
            }
            orgViewModal.call(this, selector, o);
        }
    });
}